"""
歌曲宝 搜索下载文件
"""

import json
import re
from pathlib import Path

import httpx
from lxml import etree

client = httpx.Client(base_url='https://www.gequbao.com')


def download(detail_url):
    response = client.get(detail_url)
    tree = etree.HTML(response.text)
    music_lrc = ''.join(tree.xpath('//div[@id="content-lrc"]/text()'))
    pattern = r'window\.appData\s*=\s*({.*?});'
    match = re.search(pattern, response.text, re.DOTALL)

    if not match:
        raise ValueError("未在HTML中找到 window.appData 的JSON数据")

    json_str = match.group(1)

    # 处理JSON中的特殊转义
    json_str = json_str.replace(r'\/', '/')  # 修复URL中的转义斜杠
    json_str = json_str.encode().decode('unicode_escape')  # 处理Unicode字符
    json_data = json.loads(json_str)
    music_image = json_data['mp3_cover']
    music_title = json_data['mp3_title']
    music_author = json_data['mp3_author']
    response = client.post('/api/play-url', data={'id': json_data['play_id']})
    music_url = response.json()['data']['url']
    save_path = Path('/Users/yunhai/Downloads/music')
    save_path.mkdir(parents=True, exist_ok=True)
    rename = input('rename:').strip()
    rename = rename or music_title
    with open(save_path / f'{rename}.mp3', 'wb') as f:
        f.write(client.get(music_url).content)
    save_path.joinpath(f'{rename}.lrc').write_text(music_lrc, encoding='utf-8')

    with open(save_path / f'{rename}.jpg', 'wb') as f:
        f.write(client.get(music_image).content)
    print(save_path / f'{rename}.jpg')
    print(f'{music_title} - {music_author} 下载完成')


def search():
    keyword = input('keyword:').strip()
    if not keyword:
        print('keyword is empty')
        return
    response = client.get(f'/s/{keyword}')
    tree = etree.HTML(response.text)
    items = tree.xpath('//div[@class="card-text"]/div[@class="row"]/div[1]/a')
    tabs = []
    for index, item in enumerate(items):
        detail_url = item.xpath('./@href')[0].strip()
        music_title = item.xpath('./span/span/text()')[0].strip()
        music_author = item.xpath('./small/text()')[0].strip()
        print(index + 1, detail_url, music_title, music_author)
        tabs.append({
            'detail_url': detail_url,
            'music_title': music_title,
            'music_author': music_author
        })
    select = input('download id:')
    download(tabs[int(select) - 1]['detail_url'])


search()
